﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using MS.InformationManagement.DAL.DocumentCenter;
using MS.InformationManagement.Support.Constants;
using Microsoft.Office.Server.UserProfiles;

namespace MS.InformationManagement.Core.SystemUser
{
    public class UsersManager
    {

        public static bool UserExists(SPFieldUserValue user)
        {
            using(var dc = new DCDocumentCenterDataContext(SPContext.Current.Web.Url))
            {
                var tempUser = (from currentUser in dc.UsuariosDelSistema
                                where currentUser.Id == user.LookupId
                                select currentUser).FirstOrDefault();
                return tempUser != null;
            }
        }

        public static void AddUser(SPFieldUserValue user)
        {
            using(var dc = new DCDocumentCenterDataContext(SPContext.Current.Web.Url))
            {
                var newUser = new UsuarioSistema();
                newUser.Title = user.User.Name;
                newUser.Usuario = user.LookupValue;
                newUser.UsuarioId = user.LookupId;
                dc.UsuariosDelSistema.InsertOnSubmit(newUser);
                dc.SubmitChanges();

            }
        }

        public static bool DocumentLibraryUserExists(SPFieldUserValue user)
        {
            var library = (from lib in SPContext.Current.Web.Lists.OfType<SPList>()
                           where lib.Title == user.LookupValue
                           select lib).FirstOrDefault();
            return library != null;
        }

        public static Guid CreateDocumentLibrary(SPFieldUserValue user, SPWeb currentWeb)
        {
            String userName = user.User.LoginName.Split('\\')[1];
            SPListTemplate listTemplate = currentWeb.ListTemplates[GlobalConstants.TEMPLATE_USER_LIBRARY];
            Guid newLibraryId = currentWeb.Lists.Add(userName, null, listTemplate);
            return newLibraryId;
        }

        public static Guid CreateDocumentLibrary(SPFieldUserValue user)
        {
            SPWeb currentWeb = SPContext.Current.Web;
            String userName = user.User.LoginName.Split('\\')[1];
            SPListTemplate listTemplate = currentWeb.ListTemplates[GlobalConstants.TEMPLATE_USER_LIBRARY];
            Guid newLibraryId = currentWeb.Lists.Add(userName, null, listTemplate);
            return newLibraryId;
        }


        public static void SetNewUserPermissions(SPFieldUserValue user, Guid libraryId)
        {
            SPWeb currentWeb = SPContext.Current.Web;
            currentWeb.AllowUnsafeUpdates = true;
            SPUser spuser = currentWeb.EnsureUser(user.User.LoginName);
            SPList userList = currentWeb.Lists[libraryId];
            userList.BreakRoleInheritance(false);
            SPRoleDefinitionCollection objWebRoleDefn = currentWeb.RoleDefinitions;
            SPRoleAssignment objRoleAssign = new SPRoleAssignment(user.User);
            objRoleAssign.RoleDefinitionBindings.Add(objWebRoleDefn["Colaborar"]);
            userList.RoleAssignments.Add(objRoleAssign);
            userList.Update();
            currentWeb.Update();
            currentWeb.AllowUnsafeUpdates = false;
        }


        /// <summary>
        /// Update user profile properties
        /// </summary>
        /// <param name="properties">Dictionary with properties to update key=> PropertyName, value=>PropertyValue</param>
        public static void UpdateUserProfileProperties(string userLoginName, Dictionary<string, object> properties)
        {
            UserProfile up = ProfileLoader.GetProfileLoader().GetUserProfileManager().GetUserProfile(userLoginName);
            foreach (var property in properties)
            {
                up[property.Key].Clear();
                if (!(property.Value is IEnumerable<string>))
                    up[property.Key].Add(property.Value);
                else
                {
                    var values = property.Value as IEnumerable<string>;
                    foreach (var value in values)
                        up[property.Key].Add(value);
                }
                up.Commit();
            }
        }


    }
}
